package com.bjpowernode.crm.settings.web.controller;

import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.settings.service.impl.UserServiceImpl;
import com.bjpowernode.crm.utils.MD5Util;
import com.bjpowernode.crm.utils.PrintJson;
import com.bjpowernode.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: MyCRM
 * @description:
 * @author: 玉树临风的寒
 * @create: 2020-12-14 14:37:24
 **/
public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入用户控制器");

        String path = req.getServletPath();

        if("/settings/user/login.do".equals(path)){
          login(req,resp);
        }
        /*else if("/settings/user/xxx.do".equals(path)){

        }*/
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("进入验证登录");
        String loginAct =req.getParameter("loginAct");
        String loginPwd =req.getParameter("loginPwd");
        //将密码明文形式转换为MD5密文模式
        loginPwd = MD5Util.getMD5(loginPwd);
        //接收浏览器端的IP地址
        String ip = req.getRemoteAddr();
        //未来业务层开发 同一使用代理类的形态的接口对象
        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());
        System.out.println("us 运行成功");
        try{
            User user=us.login(loginAct,loginPwd,ip);
            req.getSession().setAttribute("user",user);
            //如果程序执行到此处，说明业务层没有为controller抛出任何异常
            //表示登录成功
            /*
             {"success":true}
             */
            String str ="{\"success\":true}";
            PrintJson.printJsonFlag(resp,true);

        }catch (Exception e){
            //一旦程序进入catch语句块 说明登录失败
            //向controller抛出了异常
            e.printStackTrace();
            /*
            {"success":false,"msg":?}
             */
            String msg = e.getMessage();
            /*
            现在作为controller，需要为ajax请求提供多项信息
            可以有两种手段
             1.将多项信息打包成 map 将map解析为json
             2.创建一个Vo
                boolean success，String msg

             如果对于展现的信息 将来还会大量的使用 创建vo
             如果对于展现的信息，只有在这个需求中可以使用，使用map

             */
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg",msg);
            PrintJson.printJsonObj(resp,map);
        }

    }
}


